
#include "MutableTimer.h"

namespace toolkit {

MutableTimer::MutableTimer(float second,
             const function<bool()> &cb,
             const EventPoller::Ptr &poller,
             bool continueWhenException) {
    _poller = poller;
    _interval_second = second;
    if(!_poller){
        _poller = WorkPollerPool::Instance().getPoller();
    }
    _tag = _poller->doDelayTask((uint64_t)(_interval_second * 1000), [this , cb, continueWhenException]() {
        try {
            if (cb()) {
                //重复的任务
                return (uint64_t) (1000 * _interval_second);
            }
            //该任务不再重复
            return (uint64_t) 0;
        }catch (std::exception &ex){
            ErrorL << "执行定时器任务捕获到异常:" << ex.what();
            return continueWhenException ? (uint64_t) (1000 * _interval_second) : 0;
        }
    });
}
void MutableTimer::UpdateInterval(float second){
    _poller->async_first([this,second](){
        _interval_second = second;
    });
}
MutableTimer::~MutableTimer() {
    auto tag = _tag.lock();
    if(tag){
        tag->cancel();
    }
}

}  // namespace toolkit

